package com.qiu.greened.ui.post

import androidx.appcompat.app.AppCompatActivity
import android.os.Bundle
import android.util.Log
import android.view.*
import androidx.activity.viewModels
import androidx.lifecycle.lifecycleScope
import androidx.paging.LoadState
import androidx.recyclerview.widget.DividerItemDecoration
import androidx.recyclerview.widget.LinearLayoutManager
import com.bumptech.glide.Glide
import com.bumptech.glide.load.resource.bitmap.CircleCrop
import com.bumptech.glide.request.RequestOptions
import com.qiu.greened.R
import com.qiu.greened.adapter.PostAdapter
import com.qiu.greened.adapter.ReplyAdapter
import com.qiu.greened.databinding.ActivityPostInfoBinding
import com.qiu.greened.databinding.ActivityPostUserBinding
import com.qiu.greened.network.ServiceCreator
import com.qiu.greened.utils.MyData
import com.qiu.greened.utils.getTimeFormatText
import com.qiu.greened.utils.showToast
import kotlinx.coroutines.flow.collect
import kotlinx.coroutines.launch

class PostUserActivity : AppCompatActivity() {

    private lateinit var binding: ActivityPostUserBinding
    private val viewModel: PostUserViewModel by viewModels()
    private val postAdapter by lazy { PostAdapter() }

    private var postUserId = -1


    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        binding = ActivityPostUserBinding.inflate(layoutInflater)
        setContentView(binding.root)
        //标题栏
        supportActionBar?.let {
            it.setHomeButtonEnabled(true)
            it.setDisplayHomeAsUpEnabled(true)
            it.title = ""
        }
        val userId: Int = intent.getIntExtra("userId", -1)
        setUserData(userId) //设置用户数据
        setPostData(userId) //设置动态数据
    }
    private fun setUserData(userId: Int) {
        viewModel.loadUser(userId)
        viewModel.user.observe(this, {
            postUserId = it.userId
            binding.textName.text = it.nickName
            Glide.with(this).load(ServiceCreator.BASE_URL + it.userAvatar)
                .apply(RequestOptions.bitmapTransform(CircleCrop())).into(binding.imgUser)
            if (it.userId == MyData.userId) {
                binding.btnFollow.visibility = View.INVISIBLE
            } else {
                setFollowView(it.isFollow)
            }
        })
    }
    private fun setFollowView(bool: Boolean) {
        if (bool) {
            binding.btnFollow.text = "取消关注"
        } else {
            binding.btnFollow.text = "关注"
        }
    }
    private fun setPostData(userId: Int) {
        val linearLayoutManager = LinearLayoutManager(this)
        binding.recyclerView.layoutManager = linearLayoutManager
        binding.recyclerView.adapter = postAdapter
        lifecycleScope.launch {
            viewModel.getPagingData(userId).collect { pagingData ->
                postAdapter.submitData(pagingData)
            }
        }
        postAdapter.addLoadStateListener {
            when (it.refresh) {
                is LoadState.NotLoading -> {
                    binding.recyclerView.visibility = View.VISIBLE
                }
                is LoadState.Loading -> {
                    binding.recyclerView.visibility = View.INVISIBLE
                }
                is LoadState.Error -> {
                    val state = it.refresh as LoadState.Error
                    "Load Error: ${state.error.message}".showToast()
                }
            }
        }
        postAdapter.addOnPagesUpdatedListener {
            binding.recyclerView.scrollToPosition(0)
        }
    }

    override fun onCreateOptionsMenu(menu: Menu?): Boolean {
        menuInflater.inflate(R.menu.search_menu, menu)
        return super.onCreateOptionsMenu(menu)
    }
    override fun onOptionsItemSelected(item: MenuItem): Boolean {
        when (item.itemId) {
            android.R.id.home -> {
                finish() // back button
                return true
            }
        }
        return super.onOptionsItemSelected(item)
    }
}